package com.camera.yl.v

import android.app.AppOpsManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.Process
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.camera.base.BaseApp
import com.camera.base.WebSocketEventHandler
import com.camera.base.permission.RxPermissions
import com.camera.base.util.APPUtil
import com.camera.base.util.CameraDegreeUtil
import com.camera.base.util.ConfigSharePreferenceUtil
import com.camera.base.util.ToastUtil
import com.camera.base.v.BaseActivity
import com.camera.base.v.GridSpacingItemDecoration
import com.camera.base.wbmodels.WebModel
import com.camera.routemodule.RouterPath
import com.camera.yl.BuildConfig
import com.camera.yl.R
import com.camera.yl.adapter.SubMenuAdapter
import com.camera.yl.bean.MenuItemInfo
import com.camera.yl.databinding.ActivityMainBinding
import com.camera.yl.decoration.CyberGridDecoration
import com.camera.yl.util.CameraPopManager
import com.camera.yl.v.models.MainViewModel
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.disposables.Disposable
import java.io.File


@AndroidEntryPoint
@Route(path = RouterPath.path.main_activity)
class MainActivity: BaseActivity<ActivityMainBinding,MainViewModel>() {
    private val TAG = "MainActivity"
    override val viewModelClass: Class<MainViewModel>
        get() = MainViewModel::class.java
    
    // 主菜单列表和适配器
    private lateinit var itemsList: MutableList<MenuItemInfo>
    private lateinit var mAdapter: SubMenuAdapter
    private val rxPermissions = RxPermissions(this)

    var checkPerDisposable: Disposable? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }
    override fun getStatusBarColor(): Int{
        return R.color.title_background_color
    }
    private  val REQUEST_CODE_INSTALL_PERMISSION2 = 1002

    fun onloginclick(view: View){
        viewModel.mIMAppInterface?.let {
            if(it.hasServiceConnected()){
                ToastUtil.showLong("已登录")
            } else {
                ARouter.getInstance().build(RouterPath.path.login_activity).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
        }
    }
    
    override fun loadData() {
        Log.e(TAG, "loadData1111111111111: "+APPUtil.getVersionCode(this) )
        viewModel.sureTipsDialogEvent.observe(this){ (show, title, message) ->
            if (show == 0){
                showSureDialog(resources.getString(title)+":"+message,
                    onConfirm = {
                        //开启下载功能
                        APPUtil.installApk(this@MainActivity,viewModel.path)
                    },
                    onCancel = {
                    })
            }else if (show == 1){
                Log.e(TAG, "loadData: 直接安装")
                if(!File(viewModel.path).exists()){
                    ConfigSharePreferenceUtil.setUpgradeApk("")
                    ConfigSharePreferenceUtil.setUpgradeApkInLocal(false)
                }
                APPUtil.installApk(this@MainActivity,viewModel.path)
            }
        }
        
        mBinding.viewModel = viewModel
        
        // 保留PTT状态Fragment（如果需要）
        if(viewModel.mIMAppInterface != null){
            val pttStateFragment = ARouter.getInstance().build(RouterPath.path.ptt_fragment_state).navigation() as Fragment?
            if (pttStateFragment != null) {
                val fragmentManager: FragmentManager = supportFragmentManager
                val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
                fragmentTransaction.replace(R.id.fragment_ptt_state, pttStateFragment)
                fragmentTransaction.commit()
            }
            val imAccStateFragment = ARouter.getInstance().build(RouterPath.path.acc_fragment_state).navigation() as Fragment?
            if (imAccStateFragment != null) {
                val fragmentManager: FragmentManager = supportFragmentManager
                val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
                fragmentTransaction.replace(R.id.fl_activity_main_imstate, imAccStateFragment)
                fragmentTransaction.commit()
            }
        }else{
//            mBinding.rlMainActivityTitle.set
            viewModel.rlMainTitleHeight.value = resources.getDimensionPixelSize(com.camera.base.R.dimen.qb_px_80)
            viewModel.titleTextSize.value = resources.getDimension(com.camera.base.R.dimen.qb_px_30) / resources.displayMetrics.scaledDensity
        }
        val items = BaseApp.ylBean.items.split(",".toRegex()).toTypedArray()
        if(items.contains("gb") && BuildConfig.HasGBModule){
            //可添加国标的状态到  上部分
            val gbStatteFragment = ARouter.getInstance().build(RouterPath.path.gbstate_fragment).navigation() as Fragment?
            if (gbStatteFragment != null) {
                val fragmentManager: FragmentManager = supportFragmentManager
                val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
                fragmentTransaction.replace(R.id.fl_activity_main_gbstate, gbStatteFragment)
                fragmentTransaction.commit()
            }
        }
        // 准备菜单数据并初始化RecyclerView
        prepareMenuData(items)
        initRecyclerView()
    }
    
    /**
     * 准备所有菜单数据 - 合并原来所有Fragment的菜单项
     */
    private fun prepareMenuData(items: Array<String>) {
//        val items = BaseApp.ylBean.items.split(",".toRegex()).toTypedArray()
        itemsList = ArrayList<MenuItemInfo>()
        
        for (name in items) {
            var itemInfoM: MenuItemInfo? = null
            
            // 来自LocalFragment的菜单项
            when (name) {
                "video" -> {
                    itemInfoM = MenuItemInfo(getString(R.string.camera_fragment), R.drawable.ic_video, "video")
                }
                "file" -> {
                    itemInfoM = MenuItemInfo(getString(R.string.file_fragment), R.drawable.ic_folder, "file")
                }
                // 来自IMFragment的菜单项（只有当IM模块启用时才显示）
                "contacts" -> {
                    if (viewModel.mIMAppInterface != null) {
                        itemInfoM = MenuItemInfo(getString(R.string.contacts_fragment), R.drawable.ic_contacts, "contacts")
                    }
                }
                "chat" -> {
                    if (viewModel.mIMAppInterface != null) {
                        itemInfoM = MenuItemInfo(getString(R.string.message_fragment_ts), R.drawable.ic_chat, "chat")
                    }
                }
                "channel" -> {
                    if (viewModel.mIMAppInterface != null) {
                        itemInfoM = MenuItemInfo(getString(R.string.channl_fragment), R.drawable.ic_channel, "channel")
                    }
                }
                "channel_settings" -> {
                    if (viewModel.mIMAppInterface != null) {
                        itemInfoM = MenuItemInfo(getString(R.string.channel_settings_fragment), R.drawable.ic_channel_settings, "channel_settings")
                    }
                }
                // 对讲功能（只有当IM模块启用时才显示）
                "ptt" -> {
                    if (viewModel.mIMAppInterface != null) {
                        itemInfoM = MenuItemInfo(getString(R.string.ptt_fragment), R.drawable.ic_ptt, "ptt")
                    }
                }
                // 来自SettingFragment的菜单项
                "video_setting" -> {
                    itemInfoM = MenuItemInfo(getString(R.string.video_setting), R.drawable.ic_video_setting, "video_setting")
                }
                "sysseting" -> {
                    itemInfoM = MenuItemInfo(getString(R.string.sys_setting), R.drawable.ic_sys_setting, "sysseting")
                }
            }
            
            if (itemInfoM != null) {
                itemsList.add(itemInfoM)
            }
        }
        
        // 条件性添加平台设置（来自SettingFragment的逻辑）
        if ((items.contains("gb") && BuildConfig.HasGBModule) || BuildConfig.HasRTSP) {
            val netPlatformItem = MenuItemInfo(getString(R.string.net_platform_setting), R.drawable.ic_net_platform, "net_platform_setting")
            itemsList.add(netPlatformItem)
        }
    }
    
    /**
     * 初始化RecyclerView
     */
    private fun initRecyclerView() {
        if (itemsList.size <= 0) return
        
        val spanCount = 3
        val mGridLayoutManager = androidx.recyclerview.widget.GridLayoutManager(
            this,
            spanCount
        )
        
        // 设置SpanSizeLookup确保每个项目占据相同的空间
        mGridLayoutManager.spanSizeLookup = object : androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return 1 // 每个项目占据1个空间单位
            }
        }
        
        mBinding.rvMainMenu.layoutManager = mGridLayoutManager
        
        // 添加网格间距装饰器
        val spacing = resources.getDimensionPixelSize(com.camera.base.R.dimen.qb_px_16) // 16dp的间距
        mBinding.rvMainMenu.addItemDecoration(GridSpacingItemDecoration(spanCount, spacing, true))
        
        // 添加Cyber网格装饰器，实现HTML中的cyber-grid效果
        mBinding.rvMainMenu.addItemDecoration(CyberGridDecoration(gridSize = 20))
        
        // 设置RecyclerView性能优化
        mBinding.rvMainMenu.setHasFixedSize(true)
        
        // 设置适配器
        mAdapter = SubMenuAdapter(this, itemsList)
        mBinding.rvMainMenu.adapter = mAdapter
        
        // 设置点击监听器
        mAdapter.setClickListener { view, position ->
            val subMenu: MenuItemInfo = itemsList[position]
            onSelectMenuItem(subMenu)
        }
    }

    var ylEventHandler: WebSocketEventHandler = object : WebSocketEventHandler() {
        override fun onWebSocketMeesage(mWebModel: WebModel) {
        }
    }

    override fun initView() {
        CameraDegreeUtil.var2 = this.windowManager.defaultDisplay.rotation
        if (checkFloatPermission(this)) {
//            checkPerDisposable = rxPermissions.requestEachCombined(
//                Manifest.permission.READ_PHONE_STATE
//            )
//                .subscribe(Consumer<Permission> { permission: Permission ->
//                    if (permission.granted) {
//                        val tm = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
//                        val ccid = tm.simSerialNumber
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                        };
//                    }
//                })

        }else{
            requestSettingCanDrawOverlays();
        }
        //需要权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val hasInstallPermission = this.packageManager.canRequestPackageInstalls()
            if (!hasInstallPermission) {
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                intent.data = Uri.parse("package:" + this.packageName)
                this.startActivityForResult(intent, REQUEST_CODE_INSTALL_PERMISSION2)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 109){
            when(resultCode){
                0 -> {
                    if (checkFloatPermission(this)) {
//                        ICPCameraFactory.mIcpInterface!!.startICPCameraService()
                    }
                }
            }
        }

    }
    private fun requestSettingCanDrawOverlays() {
        val sdkInt = Build.VERSION.SDK_INT
        if (sdkInt >= 26 && !checkFloatPermission(this)) { //8.0以上
            Toast.makeText(this@MainActivity, "hint_open_manage_windhow", Toast.LENGTH_LONG).show()
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            startActivityForResult(intent, 109)
        } else if (sdkInt >= 23 && !checkFloatPermission(this)) { //6.0-8.0
            Toast.makeText(this@MainActivity, "hint_open_manage_windhow", Toast.LENGTH_LONG).show()
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            intent.data = Uri.parse("package:$packageName")
            startActivityForResult(intent, 109)
        } else { //4.4-6.0一下
        }
    }
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        APPUtil.onRequestPermissionsResult(requestCode,permissions,grantResults,this,
            File(viewModel.path)
        )
    }
    fun checkFloatPermission(context: Context): Boolean {
        if (Build.VERSION.SDK_INT < 19) return true
        return if (Build.VERSION.SDK_INT < 23) {
            try {
                var cls = Class.forName("android.content.Context")
                val declaredField = cls.getDeclaredField("APP_OPS_SERVICE")
                declaredField.isAccessible = true
                var obj: Any? = declaredField[cls] as? String ?: return false
                val str2 = obj as String
                obj = cls.getMethod("getSystemService", String::class.java).invoke(context, str2)
                cls = Class.forName("android.app.AppOpsManager")
                val declaredField2 = cls.getDeclaredField("MODE_ALLOWED")
                declaredField2.isAccessible = true
                val checkOp = cls.getMethod(
                    "checkOp", Integer.TYPE, Integer.TYPE,
                    String::class.java
                )
                val result =
                    checkOp.invoke(obj, 24, Binder.getCallingUid(), context.packageName) as Int
                result == declaredField2.getInt(cls)
            } catch (e: Exception) {
                false
            }
        } else {
            if (Build.VERSION.SDK_INT >= 26) {
                val appOpsMgr = context.getSystemService(APP_OPS_SERVICE) as AppOpsManager
                    ?: return false
                val mode = appOpsMgr.checkOpNoThrow(
                    "android:system_alert_window", Process.myUid(), context
                        .packageName
                )
                Settings.canDrawOverlays(context) || mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED
            } else {
                Settings.canDrawOverlays(context)
            }
        }
    }
    
    fun onSelectMenuItem(info: MenuItemInfo){
        when(info.args){
            "video" ->{
                ARouter.getInstance().build(RouterPath.path.camera_activity).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "video_setting" ->{
                ARouter.getInstance().build(RouterPath.path.mediaSetting_talk).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "watermark_setting" ->{
                ARouter.getInstance().build(RouterPath.path.watermark_setting_activity).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "file" ->{
                ARouter.getInstance().build(RouterPath.path.file_activity).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "contacts" ->{
                ARouter.getInstance().build(RouterPath.path.im_activity).withString("fragment_key", "contacts").withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "chat" ->{
                ARouter.getInstance().build(RouterPath.path.im_activity).withString("fragment_key", "chat").withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "channel" ->{
                ARouter.getInstance().build(RouterPath.path.im_activity).withString("fragment_key", "channel").withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "channel_settings" ->{
                ARouter.getInstance().build(RouterPath.path.im_activity).withString("fragment_key", "channel_settings").withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "ptt" ->{
                ARouter.getInstance().build(RouterPath.path.im_activity).withString("fragment_key", "ptt").withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "net_platform_setting" ->{
                ARouter.getInstance().build(RouterPath.path.net_platform_settings_activity).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
//                ARouter.getInstance().build(RouterPath.path.gbsetting_activity).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "sysseting" ->{
                ARouter.getInstance().build(RouterPath.path.syssetting_activity).withTransition(R.anim.slide_in_right, R.anim.slide_out_left).navigation()
            }
            "floating_camera" ->{
                // 启动悬浮窗相机
                startFloatingCamera()
            }

        }
    }

    override fun onBackPressed() {
//        super.onBackPressed()
        moveTaskToBack(true)
    }

    /**
     * 启动悬浮窗相机
     */
    fun startFloatingCamera() {
        CameraPopManager.startFloatingCamera(this)
    }

    override fun onDestroy() {
        checkPerDisposable?.dispose()
        super.onDestroy()

    }
}